using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Common
{
    public class MessageHelper
    {
        public struct CopyDataStruct
        {
            public IntPtr dwData;

            public int cbData;

            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        public const int WM_COPYDATA = 74;

        public const int SUCCESS = 1;

        public const int FAILED = -1;

        [DllImport("User32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("User32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref CopyDataStruct lParam);

        public static int SendMessage(string windowName, string strMsg)
        {
            if (strMsg == null)
            {
                return -1;
            }
            IntPtr intPtr = FindWindow(null, windowName);
            if (intPtr != IntPtr.Zero)
            {
                CopyDataStruct lParam = default(CopyDataStruct);
                lParam.dwData = IntPtr.Zero;
                lParam.lpData = strMsg;
                lParam.cbData = Encoding.Default.GetBytes(strMsg).Length + 1;
                int wParam = 0;
                return SendMessage(intPtr, 74, wParam, ref lParam);
            }
            return -1;
        }
    }
}
